package common.kit;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;


public class ExcelKit {
	
	FileInputStream fs ;
	HSSFWorkbook workbook ;
	HSSFSheet hs ;
	
	public HSSFSheet getHSSheet() {
		return hs ;
	}
	
	public ExcelKit(File file) {
		try {
			this.fs = FileUtils.openInputStream(file);
			this.workbook = new HSSFWorkbook(this.fs);
			this.hs = this.workbook.getSheetAt(0);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public ExcelKit() {
		this.workbook = new HSSFWorkbook();
		this.hs = workbook.createSheet();
	}
	
	public void close(){
		try {
			this.workbook.close();
			this.fs.close(); 
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Map<Integer, String> getkeyMap(String keys) {
		Map<Integer, String> map = new HashedMap<Integer, String>();
		if (StrKit.isBlank(keys)) {
			return map ;
		}
		String[] arr = keys.split(",");
		for (int i = 0; i < arr.length; i++) {
			String cur = arr[i];
			if (StrKit.notBlank(cur)) {
				map.put(i, cur);
			}
		}
		return map ;
	}
	
	public File writeExcel() {
		String path = PathKit.getWebRootPath() + "/downloadExcel" ;
		File file = new File( path );
		if (!file.exists()) {
			file.mkdirs();
		}
		file = new File( path + "/" + StrKit.getRandomUUID() + ".xls" ) ;
		try {
			file.createNewFile();
			FileOutputStream stream = FileUtils.openOutputStream(file);
			this.workbook.write(stream);
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file ;
	}
}
